//
//  AddParkTableViewController.m
//  HundPark
//
//  Created by MacBooken Rolle on 3/21/13.
//  Copyright (c) 2013 ARV IT. All rights reserved.
//

#import "AddParkTableViewController.h"
#import "AppDelegate.h"

@interface AddParkTableViewController ()

@property (weak, nonatomic) City *allParks;
@property (weak, nonatomic) IBOutlet UITextField *addParkName;
@property (weak, nonatomic) IBOutlet UITextField *addParkDistrict;
@property (weak, nonatomic) IBOutlet UITextView *addParkInfo;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *saveButton;
@property (weak, nonatomic) IBOutlet UIImageView *parkImage;
@property (weak, nonatomic) IBOutlet UIButton *addImageCamera;
@property (weak, nonatomic) IBOutlet UIButton *addPhotoCameraRoll;

- (IBAction)savePark:(UIBarButtonItem *)sender;
- (IBAction)editChange:(UITextField *)sender;
- (IBAction)addImage:(UIButton *)sender;

@end

@implementation AddParkTableViewController

CustomProgressView *customProgressView;

@synthesize park = _park;
@synthesize coordinate = _coordinate;
@synthesize allParks =_allParks;

#define DEFAULT_PARKIMAGE @"tempImage.png"

#pragma mark - Lazy Instantiation


// Lazy Instantiation
-(Park *)park
{
    if(!_park){
        _park = [[Park alloc]initWithLongitude:self.coordinate.longitude
                                      latitude:self.coordinate.latitude];
        _park.imageName = @"tempImage";
        _park.name = self.addParkName.text;
        _park.distric = self.addParkDistrict.text;
        _park.info = self.addParkInfo.text;
        
    }
    return _park;
}


// Set tempImage.png as default
-(UIImageView *)parkImage
{
    if(!_parkImage.image)
    {
        _parkImage.image = [UIImage imageNamed:DEFAULT_PARKIMAGE];
    }
    return _parkImage;
}

//Lazy Instantiation
-(City *)allParks
{
    if(!_allParks){
        AppDelegate *appDelegate =  (AppDelegate *)[[UIApplication sharedApplication ]delegate];
        _allParks = appDelegate.allParks;
    }
    
    return _allParks;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma mark - Life cycle

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // Show keyboard and put the cursor on the title bar
    [self.addParkName becomeFirstResponder];
}

-(void)viewDidLoad
{
    // Set a as delegate of City
    self.allParks.delegate = self;
    
    
    // Fake Placeholder for TextView
    self.addParkInfo.text = @"Info";
    self.addParkInfo.textColor = [UIColor lightGrayColor];
}

#pragma mark - Text field delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.addParkName) {
        // The user pressed the "return" button, change the cursor to the next field
        [self.addParkDistrict becomeFirstResponder];
    }else if (textField == self.addParkDistrict) {
        // The user pressed the "return" button, change the cursor to the next field
        [self.addParkInfo becomeFirstResponder];
    } else {
        if (self.saveButton.enabled) {
            [self savePark:nil];
        }
    }
    return YES;
}

#pragma mark - Text view delegate
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    // Fake Placeholder for TextView
    if (textView == self.addParkInfo){
        
        self.addParkInfo.text = @"";
        self.addParkInfo.textColor = [UIColor blackColor];
    }
    return YES;
}

-(void) textViewDidChange:(UITextView *)textView
{
    // Fake Placeholder for TextView    
    if(self.addParkInfo.text.length == 0){
        self.addParkInfo.textColor = [UIColor lightGrayColor];
        self.addParkInfo.text = @"Info";
        [self.addParkInfo resignFirstResponder];
    }
}

# pragma mark - Camera delegates
// Code expamle http://prassan-warrior.blogspot.se/2012/11/ios-6-iphone-camera-application.html
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        
        // Resize imgage
        self.parkImage.image = [self imageWithImage:image convertToSize:CGSizeMake(320, 160)];
        
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:finishedSavingWithError:contextInfo:), nil);
    }
}

-(void)image:(UIImage *)image finishedSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle: @"Save failed"
                              message: @"Failed to save image"
                              delegate: nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
}

// Convert to specified size 
- (UIImage *)imageWithImage:(UIImage *)image convertToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    
    float quota = size.height/image.size.height;
    float middle = size.width/2;
    float newImage_size_width = image.size.width*quota;
    
    [image drawInRect:CGRectMake((middle-(newImage_size_width/2)), 0, newImage_size_width, size.height)];
    UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return destImage;
}


#pragma mark City Delegates

-(void)finishedSavingParkInDB:(Park *)addedPark
{
    customProgressView.titleText = [NSString stringWithFormat:@"Lyckats lägga till %@ till Hundpark", self.park.name];
}

-(void)finishedSyncPlist
{
    [customProgressView.activityIndicator stopAnimating];
    
    // Send message that park object has been created
    [self.delegate addParkControllerDidFinish:self park:self.park];
}

#pragma mark - Actions

// Check whaater to use camera or camera roll
-(IBAction)addImage:(UIButton *)sender
{
    
    if ([sender.accessibilityLabel isEqualToString:@"camera"])
        [self useCamera];
    else if ([sender.accessibilityLabel isEqualToString:@"cameraRoll"])
        [self useCameraRoll];
    
}


- (void)useCamera
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = @[(NSString *) kUTTypeImage];
        imagePicker.allowsEditing = NO;
        [self presentViewController:imagePicker
                           animated:YES completion:nil];
    }
}

- (void) useCameraRoll
{
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
        UIImagePickerController *imagePicker =
        [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =
        UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = @[(NSString *) kUTTypeImage];
        imagePicker.allowsEditing = NO;
        [self presentViewController:imagePicker
                           animated:YES completion:nil];
        
    }
}

- (IBAction)savePark:(UIBarButtonItem *)sender {
    
    // ProgressView
    customProgressView = [[CustomProgressView alloc]init];
    customProgressView.titleText = [NSString stringWithFormat:@"Lägger till %@ till Hundpark", self.park.name];
    [customProgressView.activityIndicator startAnimating];
    
    // Add progess View
    [self.view addSubview:customProgressView];
    
    // Hide Keyboard
    [self.view endEditing:YES];
    
    // Add created Park to DB
    [self.allParks saveParkInDB:self.park newImage:self.parkImage.image];
    
}

- (IBAction)editChange:(UITextField *)sender {
    // Enable save button if park name added
    self.saveButton.enabled = ![self.addParkName.text isEqualToString:@""];
}
@end
